const {expressjwt: expressJWT} = require('express-jwt')
const {getPublicKeySync} = require('../utils/rsaControl')
const sendToken = require('../utils/sendToken')
const User = require('../models/User')
const REFRESH_THRESHOLD = 60 * 10
module.exports = () => {
  return expressJWT({
    secret: getPublicKeySync(), //解密秘钥
    algorithms: ["RS256"],
    isRevoked: async (req, token) => {
      // console.log('token-----: ', token)
      const {
        payload: {username, _id, exp},
      } = token;
      // console.log('username: ', username)
      // console.log('_id: ', _id)
      // console.log('exp: ', exp)
      req._id = _id;
      req.isPass = true;
      try {
        let result = await User.findById(_id);
        if (!result) {
          req.isPass = false;
          return true;
        } else {
          const isNearExpiry =
            exp - Math.floor(Date.now() / 1000) < REFRESH_THRESHOLD;
          if (isNearExpiry) {
            //设置token
            const newToken = await sendToken({
              _id,
              username,
            });
            req.newToken = newToken;
          }
          return false;
        }
      } catch (err) {
        console.log(err);
        return true;
      }
    },
  }).unless({
    path: [
      {url: "/api/login"},
      {url: "/api/getPublicKey"},
      {url: "/api/articles/random", methods: ["GET"]},
      {url: "/api/register"},
      {url: "/api/categories", methods: ["GET"]},
      {url: "/api/articles", methods: ["GET"]},
      {url: "/api/followlist", methods: ["GET"]},
      {url: "/api/navicategories", methods: ["GET"]},
      {url: "/api/favorites", methods: ["GET"]},
      {url: "/api/navigations", methods: ["GET"]},
      {url: "/api/collector", methods: ["POST"]},
      {url: /^\/api\/article\/.*/, methods: ["GET"]},
      {url: /^\/api\/authorinfo\/.*/, methods: ["GET"]},
    ],
  });
}
